import { Request, Response } from 'express';
import { User } from '../models/User';
import { Car } from '../models/Vehicle';
import { Expense } from '../models/Expense';
import { Income } from '../models/Income';
import { FuelRecord } from '../models/FuelRecord';
import { Maintenance } from '../models/Maintenance';
import { Repair } from '../models/Repair';
import { ChargingRecord } from '../models/ChargingRecord';

export class ExportController {
  /**
   * 导出用户所有数据
   */
  static async exportUserData(req: Request, res: Response) {
    try {
      const userId = (req as any).user.id;
      const { format = 'json' } = req.query;

      // 获取用户信息
      const user = await User.findById(userId).select('-password');
      if (!user) {
        return res.status(404).json({ message: '用户不存在' });
      }

      // 获取用户的所有数据
      const vehicles = await Car.find({ userId });
      const expenses = await Expense.find({ userId });
      const incomes = await Income.find({ userId });
      const fuelRecords = await FuelRecord.find({ userId });
      const maintenanceRecords = await Maintenance.find({ userId });
      const repairRecords = await Repair.find({ userId });
      const chargingRecords = await ChargingRecord.find({ userId });

      const exportData = {
        user: user.toObject(),
        vehicles: vehicles.map(v => v.toObject()),
        expenses: expenses.map(e => e.toObject()),
        incomes: incomes.map(i => i.toObject()),
        fuelRecords: fuelRecords.map(f => f.toObject()),
        maintenanceRecords: maintenanceRecords.map(m => m.toObject()),
        repairRecords: repairRecords.map(r => r.toObject()),
        chargingRecords: chargingRecords.map(c => c.toObject()),
        exportDate: new Date().toISOString(),
        totalRecords: {
          vehicles: vehicles.length,
          expenses: expenses.length,
          incomes: incomes.length,
          fuelRecords: fuelRecords.length,
          maintenanceRecords: maintenanceRecords.length,
          repairRecords: repairRecords.length,
          chargingRecords: chargingRecords.length,
        },
      };

      if (format === 'csv') {
        return ExportController.exportAsCSV(res, exportData);
      }

      res.setHeader('Content-Type', 'application/json');
      res.setHeader(
        'Content-Disposition',
        `attachment; filename="autocost_export_${Date.now()}.json"`
      );
      res.json(exportData);
    } catch (error) {
      console.error('导出数据失败:', error);
      res.status(500).json({ message: '导出数据失败' });
    }
  }

  /**
   * 导出指定时间范围的数据
   */
  static async exportDataByDateRange(req: Request, res: Response) {
    try {
      const userId = (req as any).user.id;
      const { startDate, endDate, dataType, format = 'json' } = req.query;

      if (!startDate || !endDate) {
        return res.status(400).json({ message: '请提供开始和结束日期' });
      }

      const start = new Date(startDate as string);
      const end = new Date(endDate as string);

      let exportData: any = {
        dateRange: { startDate: start, endDate: end },
        exportDate: new Date().toISOString(),
      };

      // 根据数据类型导出
      if (!dataType || dataType === 'all') {
        exportData.expenses = await Expense.find({
          userId,
          date: { $gte: start, $lte: end },
        });
        exportData.incomes = await Income.find({
          userId,
          date: { $gte: start, $lte: end },
        });
        exportData.fuelRecords = await FuelRecord.find({
          userId,
          date: { $gte: start, $lte: end },
        });
        exportData.maintenanceRecords = await Maintenance.find({
          userId,
          date: { $gte: start, $lte: end },
        });
        exportData.repairRecords = await Repair.find({
          userId,
          date: { $gte: start, $lte: end },
        });
        exportData.chargingRecords = await ChargingRecord.find({
          userId,
          date: { $gte: start, $lte: end },
        });
      } else {
        switch (dataType) {
          case 'expenses':
            exportData.expenses = await Expense.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
          case 'incomes':
            exportData.incomes = await Income.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
          case 'fuel':
            exportData.fuelRecords = await FuelRecord.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
          case 'maintenance':
            exportData.maintenanceRecords = await Maintenance.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
          case 'repair':
            exportData.repairRecords = await Repair.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
          case 'charging':
            exportData.chargingRecords = await ChargingRecord.find({
              userId,
              date: { $gte: start, $lte: end },
            });
            break;
        }
      }

      if (format === 'csv') {
        return ExportController.exportAsCSV(res, exportData);
      }

      res.setHeader('Content-Type', 'application/json');
      res.setHeader(
        'Content-Disposition',
        `attachment; filename="autocost_export_${startDate}_${endDate}_${Date.now()}.json"`
      );
      res.json(exportData);
    } catch (error) {
      console.error('导出数据失败:', error);
      res.status(500).json({ message: '导出数据失败' });
    }
  }

  /**
   * 导出费用统计报告
   */
  static async exportExpenseReport(req: Request, res: Response) {
    try {
      const userId = (req as any).user.id;
      const { year, month, format = 'json' } = req.query;

      const startDate = new Date();
      const endDate = new Date();

      if (year && month) {
        startDate.setFullYear(
          parseInt(year as string),
          parseInt(month as string) - 1,
          1
        );
        endDate.setFullYear(
          parseInt(year as string),
          parseInt(month as string),
          0
        );
      } else if (year) {
        startDate.setFullYear(parseInt(year as string), 0, 1);
        endDate.setFullYear(parseInt(year as string), 11, 31);
      } else {
        // 默认导出当前月
        startDate.setDate(1);
        endDate.setMonth(endDate.getMonth() + 1, 0);
      }

      // 获取费用数据
      const expenses = await Expense.find({
        userId,
        date: { $gte: startDate, $lte: endDate },
      });

      // 按类型统计
      const expenseStats = expenses.reduce((acc, expense) => {
        const type = expense.type;
        if (!acc[type]) {
          acc[type] = { count: 0, total: 0 };
        }
        acc[type].count++;
        acc[type].total += expense.totalAmount || 0;
        return acc;
      }, {} as any);

      // 按车辆统计
      const vehicleStats = expenses.reduce((acc, expense) => {
        const vehicleId = expense.vehicleId?.toString();
        if (!acc[vehicleId]) {
          acc[vehicleId] = { count: 0, total: 0 };
        }
        acc[vehicleId].count++;
        acc[vehicleId].total += expense.totalAmount || 0;
        return acc;
      }, {} as any);

      const report = {
        period: { startDate, endDate },
        totalExpenses: expenses.length,
        totalAmount: expenses.reduce((sum, e) => sum + (e.totalAmount || 0), 0),
        expenseStats,
        vehicleStats,
        expenses: expenses.map(e => e.toObject()),
        exportDate: new Date().toISOString(),
      };

      if (format === 'csv') {
        return ExportController.exportAsCSV(res, report);
      }

      res.setHeader('Content-Type', 'application/json');
      res.setHeader(
        'Content-Disposition',
        `attachment; filename="expense_report_${startDate.getFullYear()}_${startDate.getMonth() + 1}_${Date.now()}.json"`
      );
      res.json(report);
    } catch (error) {
      console.error('导出费用报告失败:', error);
      res.status(500).json({ message: '导出费用报告失败' });
    }
  }

  /**
   * 导出为CSV格式
   */
  private static exportAsCSV(res: Response, data: any) {
    try {
      let csvContent = '';

      // 根据数据类型生成CSV
      if (data.expenses) {
        csvContent += '费用记录\n';
        csvContent += '日期,类型,金额,车辆,备注\n';
        data.expenses.forEach((expense: any) => {
          csvContent += `${expense.date},${expense.type},${expense.totalAmount || 0},${expense.vehicleId || ''},${expense.remark || ''}\n`;
        });
        csvContent += '\n';
      }

      if (data.incomes) {
        csvContent += '收入记录\n';
        csvContent += '日期,类型,金额,备注\n';
        data.incomes.forEach((income: any) => {
          csvContent += `${income.date},${income.type},${income.amount || 0},${income.remark || ''}\n`;
        });
        csvContent += '\n';
      }

      if (data.fuelRecords) {
        csvContent += '加油记录\n';
        csvContent += '日期,加油量,金额,单价,里程数,备注\n';
        data.fuelRecords.forEach((record: any) => {
          csvContent += `${record.date},${record.fuelAmount},${record.amount},${record.fuelPrice},${record.mileage},${record.remark || ''}\n`;
        });
        csvContent += '\n';
      }

      res.setHeader('Content-Type', 'text/csv');
      res.setHeader(
        'Content-Disposition',
        `attachment; filename="autocost_export_${Date.now()}.csv"`
      );
      res.send(csvContent);
    } catch (error) {
      console.error('CSV导出失败:', error);
      res.status(500).json({ message: 'CSV导出失败' });
    }
  }

  /**
   * 创建数据备份
   */
  static async createBackup(req: Request, res: Response) {
    try {
      const userId = (req as any).user.id;

      // 获取用户所有数据
      const user = await User.findById(userId).select('-password');
      const vehicles = await Car.find({ userId });
      const expenses = await Expense.find({ userId });
      const incomes = await Income.find({ userId });
      const fuelRecords = await FuelRecord.find({ userId });
      const maintenanceRecords = await Maintenance.find({ userId });
      const repairRecords = await Repair.find({ userId });
      const chargingRecords = await ChargingRecord.find({ userId });

      const backup = {
        version: '1.0',
        backupDate: new Date().toISOString(),
        user: user?.toObject(),
        data: {
          vehicles: vehicles.map(v => v.toObject()),
          expenses: expenses.map(e => e.toObject()),
          incomes: incomes.map(i => i.toObject()),
          fuelRecords: fuelRecords.map(f => f.toObject()),
          maintenanceRecords: maintenanceRecords.map(m => m.toObject()),
          repairRecords: repairRecords.map(r => r.toObject()),
          chargingRecords: chargingRecords.map(c => c.toObject()),
        },
        summary: {
          totalVehicles: vehicles.length,
          totalExpenses: expenses.length,
          totalIncomes: incomes.length,
          totalFuelRecords: fuelRecords.length,
          totalMaintenanceRecords: maintenanceRecords.length,
          totalRepairRecords: repairRecords.length,
          totalChargingRecords: chargingRecords.length,
        },
      };

      res.json({
        message: '备份创建成功',
        backup: backup,
        downloadUrl: `/api/export/backup/${Date.now()}`,
      });
    } catch (error) {
      console.error('创建备份失败:', error);
      res.status(500).json({ message: '创建备份失败' });
    }
  }
}
